package com.lagou.edu.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
@RequestMapping("/email")
@Slf4j
public class EmailController {

    @Autowired
    private MailSender mailSender;

    @Value("${spring.mail.username}")
    private String sendMailUsername;

    @RequestMapping("/{email}/{code}")
    public boolean sendMail(@PathVariable("email") String email, @PathVariable("code") String code){
        try{
            SimpleMailMessage message = new SimpleMailMessage();
            message.setSubject("用户注册");
            message.setFrom(sendMailUsername);
            message.setTo(email);
            message.setSentDate(new Date());
            message.setText("您好，你正在进行注册操作，验证码为：" + code + "。(五分钟有效)");
            mailSender.send(message);
        }catch (Exception e){
            log.error("邮件发送验证码出现异常",e);
            return false;
        }

        return true;
    }
}
